package com.lf.web.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.json.JSONObject;

import com.opensymphony.xwork2.ActionSupport;

public class ImageService extends ActionSupport implements ServletResponseAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8295243757221772937L;

	private HttpServletResponse res;

	private File upfile;
	private String upfileFileName;
	private String upfileContentType;
	private String path = "";

	public void setUpfile(File upfile) {
		this.upfile = upfile;
	}

	public void setUpfileFileName(String upfileFileName) {
		this.upfileFileName = upfileFileName;
	}

	public void setUpfileContentType(String upfileContentType) {
		this.upfileContentType = upfileContentType;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public void upload() throws IOException {
		JSONObject json = new JSONObject();
		Date date = new Date();
		File file = new File(ServletActionContext.getServletContext()
				.getRealPath("/") + path + "/" + TimePath(date));
		if (!file.exists()) {
			file.mkdirs();
		}
		File savefile = new File(file.toString() + "/" + TimeFile(date));
		if (upfile.renameTo(savefile)) {

			json.put("code", 1);
			json.put("msg", "文件上传成功!");
			json.put("url", path + "/" + TimePath(date) + "/" + TimeFile(date));
		} else {
			json.put("code", 0);
			json.put("msg", "文件保存失败!");
		}
		res.getWriter().write(" " + json.toString());
	}

	private String TimeFile(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("ddHHmmssSSS");
		return sdf.format(date)
				+ upfileFileName.substring(upfileFileName.lastIndexOf("."));
	}

	private String TimePath(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		return sdf.format(date);
	}

	@Override
	public void setServletResponse(HttpServletResponse res) {
		this.res = res;
	}
}
